<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <!--        <a-button type="primary" icon="printer" @click="openPrintPreview">打印预览</a-button>-->
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="出库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outboundType">
              <j-dict-select-tag
                type="list"
                v-model="model.outboundType"
                dictCode="ck_type"
                placeholder="请选择出库类型"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="领料仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseNo">
              <j-search-select-tag v-model="model.warehouseNo" dict="erp_warehouse,name,code" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="上级单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="superiorOrderNumber"
            >
              <a-input v-model="model.superiorOrderNumber" placeholder="请输入上级单号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="出库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outboundDate">
              <j-date placeholder="请选择出库日期" v-model="model.outboundDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierId">
              <j-search-select-tag v-model="model.supplierId" dict="erp_supplier,name,id" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cutomerName">
              <a-input v-model="model.cutomerName" placeholder="请输入客户名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="部门车间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departmentWorkshop">
              <j-search-select-tag v-model="model.departmentWorkshop" dict="sys_depart,depart_name,org_code" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择创建日期"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="出库信息" :key="refKeys[0]" :forceRender="true">
        <div class="table-operator">
          <a-button @click="handleAddInformations" :disabled="formDisabled" type="primary" icon="plus">新增</a-button>
        </div>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussOutboundOrderInformationTable.loading"
          :columns="bussOutboundOrderInformationTable.columns"
          :dataSource="bussOutboundOrderInformationTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="false"
          @edit-closed="handleEditClosed"
          :cell-style="cellStyle"
        >
          <template v-slot:action="{ row }">
            <a :disabled="formDisabled" @click="deleteRow(row)">删除</a>
          </template>
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="明细信息" :key="refKeys[1]" :forceRender="true">
        <a-table
          ref="table"
          size="middle"
          :rowKey="(record) => record.rowKey"
          class="j-table-force-nowrap1"
          :scroll="{ x: true }"
          :columns="bussOutboundOrderDetailTable.columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :expandedRowKeys="bussOutboundOrderDetailTable.expandedRowKeys"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          @change="handleTableChange"
          @expand="handleExpand"
          v-bind="tableProps"
        >
          <template slot="meUnit" slot-scope="text">
            <span>{{ unitDictOptions[text] }}</span>
          </template>
          <template v-if="record.parent == 0" slot="quantity" slot-scope="text, record, index">
            <a-input-number
              :disabled="formDisabled"
              :style="{ backgroundColor: '#00FFFF' }"
              :min="0"
              :max="record.availableQuantity"
              v-model="record.quantity"
              @change="onCellChange(record)"
            />
          </template>
          <!--          <template v-if="record.parent == 0" slot="quantity" slot-scope="text, record">-->
          <!--            <editnumber-cell :text="text" @change="onCellChange(record, 'quantity', $event)" ></editnumber-cell>-->
          <!--          </template>-->
          <!--          <span slot="action" slot-scope="text, record">-->
          <!--&lt;!&ndash;          <a v-if="record.parent == 1" @click="handleAddChild(record)">添加明细</a>&ndash;&gt;-->

          <!--&lt;!&ndash;          <a-divider type="vertical" />&ndash;&gt;-->
          <!--            <a-popconfirm v-if="record.parent == 0"  title="确定删除吗?" @confirm="() => handleDeleteNode(record)" placement="topLeft">-->
          <!--                  <a>删除</a>-->
          <!--            </a-popconfirm>-->
          <!--        </span>-->
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <buss-inventory-list-modal ref="selectInventory" @handlerOk="inventoryOk" :category="category" checkval="checkbox">
    </buss-inventory-list-modal>
    <buss-inbound-list-modal
      ref="selectInbound"
      @inboundOk="inboundOk"
      :category="inventory"
      cheJeecgListMixinckval="checkbox"
    >
    </buss-inbound-list-modal>
  </a-spin>
</template>

<script>
import { getAction, postAction, putAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue, randomNumber, randomUUID } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import estar from '../../../estar/oa/util/estar'
import BussInventoryListModal from '@comp/base/modal/BussInventoryListModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import EditableCell from '@comp/table/EditableCell'
import EditnumberCell from '@comp/table/EditnumberCell'
import BussInboundListModal from '@comp/base/modal/BussInboundListModal'
import moment from 'dayjs'
import store from '@/store'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'

export default {
  name: 'BussOutboundOrderManagementForm',
  mixins: [JVxeTableModelMixin, JeecgListMixin],
  components: {
    JFormContainer,
    BussInventoryListModal,
    EditableCell,
    BussInboundListModal,
    EditnumberCell,
  },
  data() {
    return {
      procSelectRows: [],
      category: '4',
      inventory: '',
      selectedRowKeys: [],
      selectionRows: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      detailTemp: {},
      model: {
        outboundType: '',
        warehouseNo: '',
        code: '',
        outboundDate: '',
        createTime: '',
      },
      mainMap: new Map(),
      detailMap: new Map(),
      validatorRules: {
        outboundType: [{ required: true, message: '请选择出库类型!' }],
        warehouseNo: [{ required: true, message: '请选择仓库!' }],
      },
      dataSource: [],
      refKeys: ['bussOutboundOrderInformation'],
      tableKeys: ['bussOutboundOrderInformation'],
      activeKey: 'bussOutboundOrderInformation',
      // 出库单信息
      bussOutboundOrderInformationTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编号',
            key: 'materialCode',
            // type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '客户物料编号',
            key: 'customerMaterialCode',
            // type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'materialName',
            // type: JVXETypes.select,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'noneSpec',
            // type: JVXETypes.input,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '主计量',
            key: 'meUnit',
            type: JVXETypes.select,
            width: '100px',
            dictCode: 'ji_unit',
            disabled: true,
          },
          {
            title: '数量',
            key: 'quantity',
            type: JVXETypes.inputNumber,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '库存数量',
            key: 'inventoryQuantity',
            // type: JVXETypes.input,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          // {
          //   title: '占用库存',
          //   key: 'occupyInventory',
          //    // type: JVXETypes.input,
          //   width:"80px",
          //   placeholder: '请输入${title}',
          //   defaultValue:'',
          // },
          {
            title: '可用数量',
            key: 'availableQuantity',
            // type: JVXETypes.input,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '辅助单位',
            key: 'auUnit',
            // type: JVXETypes.input,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '辅助数量',
            key: 'auQuantity',
            // type: JVXETypes.input,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '辅助库存数量',
            key: 'auInQuantity',
            // type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '占用辅助库存',
            key: 'occupyAuInventory',
            // type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '换算率',
            key: 'conversionRate',
            type: JVXETypes.inputNumber,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      // 出库单明细
      url: {
        list: '/outbound/bussOutboundOrderDetail/rootList',
        childList: '/outbound/bussOutboundOrderManagement/queryOutboundOrderDetailByMainId',
        getChildListBatch: '/outbound/bussOutboundOrderDetail/getChildListBatch',
        add: '/outbound/bussOutboundOrderManagement/add',
        edit: '/outbound/bussOutboundOrderManagement/edit',
        queryById: '/outbound/bussOutboundOrderManagement/queryById',
        bussOutboundOrderInformation: {
          list: '/outbound/bussOutboundOrderManagement/queryBussOutboundOrderInformationByMainId',
        },
        queryTslProMaterialPickBillDetailByMainId:
          '/pro/tslProMaterialPickBill/queryTslProMaterialPickBillDetailByMainId',
      },
      bussOutboundOrderDetailTable: {
        columns: [
          {
            title: '物料名称',
            align: 'left',
            dataIndex: 'materialName',
            width: 120,
          },
          {
            title: '物料编号',
            align: 'left',
            dataIndex: 'materialCode',
            width: 120,
          },
          {
            title: '规格型号',
            align: 'left',
            dataIndex: 'noneSpec',
            width: 120,
          },
          {
            title: '主计量',
            align: 'left',
            dataIndex: 'meUnit',
            scopedSlots: { customRender: 'meUnit' },
            width: 70,
          },
          {
            title: '数量',
            align: 'left',
            dataIndex: 'quantity',
            scopedSlots: { customRender: 'quantity' },
            width: 120,
          },
          {
            title: '批次号',
            align: 'left',
            dataIndex: 'batchNumber',
            width: 120,
          },
          {
            title: '物料批号',
            align: 'left',
            dataIndex: 'materialBatchNumber',
            width: 120,
          },
          {
            title: '库位',
            align: 'left',
            dataIndex: 'warehouseLocation',
            width: 120,
          },
          {
            title: '入库数量',
            align: 'left',
            dataIndex: 'inventoryQuantity',
            width: 120,
          },
          {
            title: '已出数量',
            align: 'left',
            dataIndex: 'outputQuantity',
            width: 120,
          },
          {
            title: '可用数量',
            align: 'left',
            dataIndex: 'availableQuantity',
            width: 120,
          },
          {
            title: '占用数量',
            align: 'left',
            dataIndex: 'occupationQuantity',
            width: 120,
          },
          {
            title: '入库单号',
            align: 'left',
            dataIndex: 'warehousingCode',
            width: 120,
          },
          {
            title: '入库日期',
            align: 'left',
            dataIndex: 'warehousingDate',
            width: 90,
          },
          {
            title: '限用日期',
            align: 'left',
            dataIndex: 'restrictedDate',
            width: 90,
          },
          {
            title: '供应商',
            align: 'left',
            dataIndex: 'supplierName',
            width: 150,
          },
          {
            title: '生产车间',
            align: 'left',
            dataIndex: 'productionWorkshop_dictText',
            width: 120,
          },
          {
            title: '客户名称',
            align: 'left',
            dataIndex: 'customerName',
            width: 120,
          },
          {
            title: '宝洁供应商编码',
            align: 'left',
            dataIndex: 'bjSupplierCode',
            width: 120,
          },
          {
            title: '宝洁供应商',
            align: 'left',
            dataIndex: 'bjSupplierName',
            width: 120,
          },
          {
            title: '宝洁单号',
            align: 'left',
            dataIndex: 'bjNo',
            width: 120,
          },
          {
            title: '辅助单位',
            align: 'left',
            dataIndex: 'auUnit_dictText',
            width: 120,
          },
          {
            title: '辅助数量',
            align: 'left',
            dataIndex: 'auQuantity',
            width: 120,
          },
          {
            title: '入库辅助数量',
            align: 'left',
            dataIndex: 'inAuQuantity',
            width: 120,
          },
          {
            title: '已出辅助数量',
            align: 'left',
            dataIndex: 'outAuQuantity',
            width: 120,
          },
          {
            title: '占用辅助数量',
            align: 'left',
            dataIndex: 'occupationAuQuantity',
            width: 120,
          },
          {
            title: '单位换算率',
            align: 'left',
            dataIndex: 'conversionRate',
            width: 120,
          },
          {
            title: '备注',
            align: 'left',
            dataIndex: 'remark',
            width: 120,
          },
          {
            title: '订单编号',
            align: 'left',
            dataIndex: 'orderNo',
            width: 120,
          },
          // {
          //   title: '操作',
          //   dataIndex: 'action',
          //   align:"center",
          //   fixed:"right",
          //   width:147,
          //   scopedSlots: { customRender: 'action' },
          // }
        ],
        url: {
          list: '/outbound/bussOutboundOrderDetail/rootList',
          childList: '/outbound/bussOutboundOrderDetail/childList',
          getChildListBatch: '/outbound/bussOutboundOrderDetail/getChildListBatch',
          queryNoticeListByWareHouseAndMaterialCode: '/outbound/bussOutboundOrderDetail/getChildListBatch', //根据物料编号和仓库查询入库通知单详情和入库单数据
          delete: '/outbound/bussOutboundOrderDetail/delete',
          deleteBatch: '/outbound/bussOutboundOrderDetail/deleteBatch',
          exportXlsUrl: '/outbound/bussOutboundOrderDetail/exportXls',
          importExcelUrl: 'outbound/bussOutboundOrderDetail/importExcel',
        },
        expandedRowKeys: [],
        hasChildrenField: 'hasChild',
        pidField: 'pid',
        dictOptions: {},
        loadParent: false,
        superFieldList: [],
      },
      unitDictOptions: {},
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => (_this.selectedRowKeys = selectedRowKeys),
        },
      }
    },
  },
  created() {
    let time = estar.toDate(new Date(), 'yyyy-MM-dd')
    let startTime = estar.toDate(new Date(), 'yyyy-MM-dd HH:mm:ss')
    this.model.outboundDate = time
    this.model.createTime = startTime
    this.getSuperFieldList()
    this.initDictConfig()
  },

  methods: {
    initDictConfig() {
      //初始化字典 - 主单位
      console.log('---------------初始化字典')
      initDictOptions('ji_unit').then((res) => {
        var unitDictOptions = this.unitDictOptions
        console.log('---------------请求完成')
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            unitDictOptions[item.value] = item.label
          })
        }
        this.unitDictOptions = unitDictOptions
      })
    },
    handleValueChange({ row, column, value, oldValue }) {
      const field = column.property // 变更列的字段名

      if (field === 'quantity') {
        var max = parseFloat(row.availableQuantity)
        var num = parseFloat(row.quantity)
        // var zhanyong = 0;
        // if (row.occupyInventory != null){
        //   zhanyong = parseFloat(row.occupyInventory);
        // }
        // var keyong = num - zhanyong;
        if (num > max) {
          this.$message.error('输入的数量大于可用数量！')
        } else {
          this.mainMap.set(row.materialId, row.quantity)
        }
      }
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/ckd'
      putAction(url, { name: '出库单编码' }).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
        }
      })
    },
    inventoryOk(row) {
      console.log(row, 'inventoryOk')

      this.getInventoryDetail(row)
    },
    getInventoryDetail(objList) {
      let _this = this
      postAction('/inventory/bussInventory/queryByIds', { ids: objList }).then((res) => {
        console.log(res.result, 'inventoryOkResult')
        let erpGoodsList = res.result
        erpGoodsList.forEach(function (item, index) {
          console.log(item, index)
          let detail = {}
          let details = {}
          // detail.inventoryId = item.id;
          detail.materialId = item.materialId
          detail.materialCode = item.materialCode
          detail.materialName = item.materialName
          detail.noneSpec = item.noneSpec
          detail.meUnit = item.meUnit
          // detail.quantity = item.quantity;
          //循环遍历赋值对应物料的数量
          objList.forEach(function (pickItem, index) {
            console.log(item.materialId)
            console.log(pickItem.materialId)
            if (item.materialId === pickItem.materialId) {
              console.log('相等')
              detail.quantity = pickItem.quantity
            }
          })
          detail.inventoryQuantity = item.quantity
          detail.availableQuantity = item.availableQuantity
          console.log(_this.bussOutboundOrderInformationTable.dataSource)
          _this.filterPackageId(item.materialId)
          _this.bussOutboundOrderInformationTable.dataSource.push(detail)
          // details.inventoryId = item.id;
          details.materialId = item.materialId
          details.materialCode = item.materialCode
          details.materialName = item.materialName
          details.id = randomUUID()
          // details.noneSpec = item.noneSpec;
          // details.meUnit = item.meUnit;
          details.rowKey = details.id
          details.parent = 1
          details.isLeaf = 0
          details.hasChild = '1'
          _this.dataSource.push(details)
          _this.bussOutboundOrderDetailTable.expandedRowKeys.push(details.id)
          let detailList = item.bussInventoryDetailsList
          const listMap = new Map()
          detailList.forEach(function (ite, index) {
            //加载明细信息  todo 库存暂时没有宝洁的单号，宝洁供应商
            let pid = details.id
            // console.log(this.bussOutboundOrderDetailTable.expandedRowKeys)
            // if (this.bussOutboundOrderDetailTable.expandedRowKeys.join(',').includes(pid)) {
            let mapList = listMap.get(pid)
            if (mapList == null) {
              mapList = []
            }
            let detail1 = {}
            detail1.pid = details.id

            detail1.inventoryId = ite.id
            detail1.rowKey = ite.id
            detail1.storageMaterialId = ite.inventoryId
            detail1.materialId = ite.materialId
            detail1.materialCode = ite.materialCode
            detail1.materialName = ite.materialName
            detail1.noneSpec = ite.noneSpec
            detail1.meUnit = ite.meUnit
            detail1.meUnit_dictText = ite.meUnit_dictText
            detail1.inventoryQuantity = ite.inventoryQuantity
            detail1.availableQuantity =
              parseFloat(ite.inventoryQuantity) - parseFloat(ite.occupationQuantity) - parseFloat(ite.outboundQuantity)
            detail1.occupationQuantity = ite.occupationQuantity
            detail1.outputQuantity = ite.outboundQuantity
            // detail1.quantity = ite.quantity.toString();
            detail1.batchNumber = ite.batch
            detail1.materialBatchNumber = ite.materialBatchNumber
            detail1.warehouseLocation = ite.warehouseLocation
            detail1.warehousingId = ite.storageId
            detail1.warehousingCode = ite.code
            detail1.warehousingDate = ite.enterDate
            detail1.restrictedDate = ite.restrictedDate
            detail1.bjSupplierCode = ite.bjSupplierCode
            detail1.bjSupplierName = ite.bjSupplier
            detail1.bjNo = ite.bjOrder
            detail1.supplierId = ite.supplierId
            detail1.supplierName = ite.supplierName
            detail1.parent = 0
            detail1.isLeaf = 1
            detail1.id = randomUUID()
            console.log(detail1)
            //todo 明细入库信息未附值
            mapList.push(detail1)
            listMap.set(pid, mapList)
            // }
          })
          console.log(listMap)
          let childrenMap = listMap
          let fn = (list) => {
            if (list) {
              list.forEach((data) => {
                if (data.id === details.id && _this.bussOutboundOrderDetailTable.expandedRowKeys.includes(data.id)) {
                  // data.hasChild = '1';
                  data.children = _this.getDataByResult(childrenMap.get(data.id))
                  // fn(data.children)
                }
              })
            }
          }
          fn(_this.dataSource)
          console.log(_this.dataSource)
          _this.dataSource = _this.getDataByResult(_this.dataSource)
        })
        _this.bussOutboundOrderInformationTable.dataSource.forEach(function (item, index) {
          _this.dealOutRows(item)
        })
      })
    },
    filterPackageId(materialId) {
      this.bussOutboundOrderInformationTable.dataSource = this.bussOutboundOrderInformationTable.dataSource.filter(
        function (item) {
          return item.materialId !== materialId
        }
      )
      const col = this.dataSource.filter((item) => item.materialId === materialId)
      if (col != null) {
        const colindex = this.dataSource.indexOf(col[0])
        if (colindex !== -1) {
          this.dataSource.splice(colindex, 1)
        }
      }
    },
    handleAddInformations() {
      if (!this.model.warehouseNo) {
        this.$message.error('请先选择仓库！')
        return
      }
      this.$refs.selectInventory.add()
      this.$refs.selectInventory.title = '选择物料'
      this.$refs.selectInventory.disableSubmit = false
    },
    deleteRow(row) {
      console.log(row)
      // 删除指定行
      const index = this.bussOutboundOrderInformationTable.dataSource.indexOf(row)
      if (index !== -1) {
        this.bussOutboundOrderInformationTable.dataSource.splice(index, 1)
        const col = this.dataSource.filter((item) => item.materialId === row.materialId)
        if (col != null) {
          const colindex = this.dataSource.indexOf(col[0])
          if (colindex !== -1) {
            this.dataSource.splice(colindex, 1)
          }
        }
      }
    },
    handleDeleteNode(row) {
      // 删除指定行
      for (let item of this.dataSource) {
        if (item.hasOwnProperty('children')) {
          const index = item.children.indexOf(row)
          if (index !== -1) {
            item.children.splice(index, 1)
          }
        }
      }
      this.dataSource = [...this.dataSource]
    },
    handleAddChild(row) {
      this.detailTemp = row
      this.bussOutboundOrderDetailTable.expandedRowKeys.push(row.id)
      console.log(row)
      //todo 入库明细弹框内容
      this.$refs.selectInbound.add()
      this.$refs.selectInbound.title = '选择入库明细'
      this.$refs.selectInbound.disableSubmit = false
    },
    inboundOk(row) {
      let _this = this
      console.log(row)
      postAction('/org.jeecg.modules.business/bussStorage/queryDetailByIds', { ids: row }).then((res) => {
        console.log(res.result)
        let erpGoodsList = res.result
        const listMap = new Map()
        for (let item of erpGoodsList) {
          let pid = this.detailTemp.id
          console.log(this.bussOutboundOrderDetailTable.expandedRowKeys)
          if (this.bussOutboundOrderDetailTable.expandedRowKeys.join(',').includes(pid)) {
            let mapList = listMap.get(pid)
            if (mapList == null) {
              mapList = []
            }
            let detail = {}
            detail.pid = this.detailTemp.id
            detail.materialId = item.materialId
            detail.materialCode = item.materialCode
            detail.materialName = item.materialName
            detail.noneSpec = item.spec
            detail.meUnit = item.unit
            detail.inventoryQuantity = item.num
            detail.batchNumber = item.materialCode
            detail.materialBatchNumber = item.materialName
            detail.warehouseLocation = item.storehouse
            detail.warehousingCode = item.code
            detail.warehousingDate = item.storageDate
            detail.restrictedDate = item.expiryDate
            detail.supplierId = item.supplierId
            detail.supplierName = item.supplierName
            detail.parent = 0
            detail.isLeaf = 1
            detail.id = randomUUID()
            console.log(detail)
            //todo 明细入库信息未附值
            mapList.push(detail)
            listMap.set(pid, mapList)
          }
        }
        console.log(listMap)
        let childrenMap = listMap
        let fn = (list) => {
          if (list) {
            list.forEach((data) => {
              if (
                data.id === this.detailTemp.id &&
                this.bussOutboundOrderDetailTable.expandedRowKeys.includes(data.id)
              ) {
                // data.hasChild = '1';
                data.children = this.getDataByResult(childrenMap.get(data.id))
                // fn(data.children)
              }
            })
          }
        }
        fn(_this.dataSource)
        console.log(_this.dataSource)
        this.dataSource = this.getDataByResult(_this.dataSource)
      })
    },
    addBefore() {
      this.bussOutboundOrderInformationTable.dataSource = []
      this.getSequenceNum()
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    addProc() {
      if (this.procSelectRows.length > 0) {
        const rows = this.procSelectRows
        console.log('-----------------------------------------rows')

        console.log(rows)
        //赋值出库类型,上级单号,领料仓库,部门车间
        //通过该方法新增的出库单默认为生产领料出库
        this.model.outboundType = 2
        this.model.superiorOrderNumber = rows[0].code
        this.model.warehouseNo = rows[0].wareNo
        this.model.departmentWorkshop = rows[0].workshopCode
        //todo 通过id找对应的领料单,查询对应的库存跟明细返回
        console.log('完成')
        this.getPickBillList(rows[0].id)
        console.log('完成')
      }
    },

    //根据领料单获取领料单详情列表
    getPickBillList(billId, warehouseNo) {
      console.log('调用方法')
      console.log(this.url.queryTslProMaterialPickBillDetailByMainId)
      getAction(this.url.queryTslProMaterialPickBillDetailByMainId, { id: billId }).then((res) => {
        console.log(res)
        if (res.success) {
          this.getInventoryDetail(res.result, warehouseNo)
          console.log('r-------------------------------es')
          console.log(res)
        }
      })
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      console.log('123')
      console.log(this.dataSource)
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.bussOutboundOrderInformation.list,
          params,
          this.bussOutboundOrderInformationTable
        )
        getAction(this.url.childList, params).then((res) => {
          if (res.success) {
            console.log(res.result)
            this.dataSource = res.result.map((item) => {
              return { ...item, rowKey: item.id }
            })
            setTimeout(() => {
              console.log(this.dataSource)
              console.log('2322')
              this.dataSource.map((item) => {
                console.log(item.children)
                if (item.children != null) {
                  item.children.map((info) => {
                    this.selectedRowKeys.push(info.id)
                  })
                }
              })
              const rows = this.dataSource.map((item) => {
                //判断是否标记了带有子节点
                if (item.children != null) {
                  item.children.map((info) => {
                    this.selectionRows.push(info)
                  })
                }
              })
            }, 1000)
          }
        })
      }
      console.log('123')
      console.log(this.dataSource)
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      if (allValues.tablesValue[0].tableData.length < 1) {
        this.$message.error('请添加出库单信息！')
        return false
      }
      if (this.selectionRows.length < 1) {
        this.$message.error('请勾选出库的明细信息！')
        return false
      } else {
        const listMap = new Map()
        console.log(this.selectionRows)
        for (let item of this.selectionRows) {
          if (item.parent === 1 && this.selectionRows.length === 1) {
            this.$message.error('请勾选正确的明细信息！')
            return false
          }
          if (item.parent === 1) {
            break
          }
          console.log(item.quantity)
          if (item.quantity == null) {
            this.$message.error('请在勾选的明细信息中输入数量！')
            return false
          }

          //统计勾选的明细信息
          let quantity = listMap.get(item.materialId)
          if (quantity == null) {
            quantity = 0
          }
          if (item.quantity !== null && quantity==0) {
            quantity = quantity + parseFloat(item.quantity)
            listMap.set(item.materialId, quantity)
          }
        }
        let infoList = this.bussOutboundOrderInformationTable.dataSource
        for (let data of infoList) {
          console.log(data.quantity)
          if (data.quantity == null || data.quantity === '') {
            this.$message.error('请在出库信息中输入数量！')
            return false
          }
          let quantity = listMap.get(data.materialId)
          console.log("------------------")
          console.log(quantity)
          console.log( data.quantity)
          if (quantity != data.quantity) {
            this.$message.error(data.materialName + '的出库信息数量跟明细中总数量不一致！')
            return false
          }
        }
      }
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      console.log('allValues')
      console.log(allValues)
      console.log(this.bussOutboundOrderDetailTable)
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        bussOutboundOrderInformationList: allValues.tablesValue[0].tableData,
        outboundOrderDetailList: this.selectionRows,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        console.log('展开')

        console.log(this.dataSource)
        this.bussOutboundOrderDetailTable.expandedRowKeys.push(record.id)
        if (record.children.length > 0) {
          console.log('123')
          // getAction(this.url.childList, params).then((res) => {
          //   if (res.success) {
          //     if (res.result.records) {
          //       record.children = this.getDataByResult(res.result)
          this.dataSource = [...this.dataSource]
          //   } else {
          //     record.children = ''
          //     record.hasChildrenField = '0'
          //   }
          // } else {
          //   this.$message.warning(res.message)
          // }
          // })
        }
      } else {
        console.log('关闭')

        let keyIndex = this.bussOutboundOrderDetailTable.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.bussOutboundOrderDetailTable.expandedRowKeys.splice(keyIndex, 1)
        }
      }
    },
    getDataByResult(result) {
      if (result) {
        return result.map((item) => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    onCellChange(record) {
      console.log(record)
      const newData = this.dataSource
      this.dataSource = [...newData]
      console.log(this.dataSource)
      // console.log(value);
      // let _this = this;
      // var max = parseFloat(record.inventoryQuantity);
      // var out = 0;
      // var zhanyong = 0;
      // if (record.outputQuantity != null) {
      //   out = parseFloat(record.outputQuantity);
      // }
      // if (record.occupationQuantity != null) {
      //   zhanyong = parseFloat(record.occupationQuantity);
      // }
      // max = max - out - zhanyong;
      // var quantity = parseFloat(value);
      // console.log(max)
      // console.log(quantity)
      // if (quantity > max){
      //   record.quantity = 0
      //   _this.$message.error("输入的数量大于库存数量！")
      //   return
      // }else{
      //   _this.$set(record, dataIndex,value)
      // const listMap = new Map();
      //勾选的总数量赋值出库单信息数量
      // let list = _this.selectionRows;
      // list.forEach(data => {
      //   let mapList = listMap.get(data.materialId);
      //   if (mapList == null) {
      //     mapList = [];
      //   }
      //   let detail = {};
      //   if (data.quantity !== null) {
      //     detail.id = data.inventoryId;
      //     detail.quantity = data.quantity;
      //     mapList.push(detail);
      //   }
      //   listMap.set(data.materialId,mapList);
      // })
      // let infoList = _this.bussOutboundOrderInformationTable.dataSource;
      // infoList.forEach(data => {
      //   var num = 0;
      //   let mapList = listMap.get(data.materialId);
      //   if (mapList != null) {
      //     mapList.forEach(detail => {
      //       if (detail.quantity != null) {
      //         num = num + parseFloat(detail.quantity);
      //       }
      //     })
      //   }
      //   data.quantity = num;
      // })
      // _this.bussOutboundOrderInformationTable.dataSource = infoList;
      // }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      console.log('gouxuan')
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
      // let _this = this;
      // console.log(selectedRowKeys)
      // console.log(selectionRows)
      // const listMap = new Map();
      // //勾选的总数量赋值出库单信息数量
      // let list = _this.selectionRows;
      // list.forEach(data => {
      //   // let num = listMap.get(data.materialId)
      //   let mapList = listMap.get(data.materialId);
      //   if (mapList == null) {
      //     mapList = [];
      //   }
      //   let detail = {};
      //   if (data.quantity !== null) {
      //     detail.id = data.inventoryId;
      //     detail.quantity = data.quantity;
      //     mapList.push(detail);
      //   }
      //   listMap.set(data.materialId,mapList);
      // })
      // console.log(listMap)
      // let infoList = _this.bussOutboundOrderInformationTable.dataSource;
      // console.log(infoList)
      // infoList.forEach(data => {
      //   console.log(data)
      //   var quantity = 0;
      //   let mapList = listMap.get(data.materialId);
      //   if (mapList != null) {
      //     mapList.forEach(detail => {
      //       if (detail.quantity != null) {
      //         quantity = quantity + parseFloat(detail.quantity);
      //       }
      //     })
      //   }
      //   data.quantity = quantity;
      // })
      // console.log(infoList)
      // _this.bussOutboundOrderInformationTable.dataSource = infoList;
      // console.log(_this.bussOutboundOrderInformationTable.dataSource);
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'informationId', text: '出库信息ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'materialId', text: '物料ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'materialCode', text: '物料编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'materialName', text: '物料名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'noneSpec', text: '规格型号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'meUnit', text: '主计量', dictCode: 'ji_unit' })
      fieldList.push({ type: 'BigDecimal', value: 'quantity', text: '数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'batchNumber', text: '批次号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'materialBatchNumber', text: '物料批号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'warehouseLocation', text: '库位', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'inventoryQuantity', text: '入库数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'outputQuantity', text: '已出数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'bjSupplierCode', text: '宝洁供应商编码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'bjSupplierName', text: '宝洁供应商', dictCode: '' })
      fieldList.push({ type: 'string', value: 'warehousingId', text: '入库ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'warehousingCode', text: '入库单号', dictCode: '' })
      fieldList.push({ type: 'datetime', value: 'warehousingDate', text: '入库日期' })
      fieldList.push({ type: 'datetime', value: 'restrictedDate', text: '限用日期' })
      fieldList.push({ type: 'string', value: 'bjNo', text: '宝洁单号', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'occupationQuantity', text: '占用数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'auUnit', text: '辅助单位', dictCode: 'zl_unit' })
      fieldList.push({ type: 'BigDecimal', value: 'auQuantity', text: '辅助数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'inAuQuantity', text: '入库辅助数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'outAuQuantity', text: '已出辅助数量', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'occupationAuQuantity', text: '占用辅助数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'conversionRate', text: '单位换算率', dictCode: '' })
      fieldList.push({ type: 'string', value: 'supplierId', text: '供应商', dictCode: 'erp_supplier,name,id' })
      fieldList.push({
        type: 'string',
        value: 'productionWorkshop',
        text: '生产车间',
        dictCode: 'sys_depart,depart_name,id',
      })
      fieldList.push({ type: 'string', value: 'customerName', text: '客户名称', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'remark', text: '备注', dictCode: '' })
      fieldList.push({ type: 'string', value: 'orderNo', text: '订单编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'pid', text: '父级节点', dictCode: '' })
      this.superFieldList = fieldList
    },
    openPrintPreview() {
      if (this.model.id == null) {
        if (
          this.bussOutboundOrderInformationTable.dataSource == null ||
          this.bussOutboundOrderInformationTable.dataSource.length < 1
        ) {
          this.$message.error('请添加出库信息再预览')
          return
        }
      }
      console.log(store)
      var name = store.getters.userInfo.realname
      const params = {
        templateId: '979158814296924160',
        title: '出库单',
        code: this.model.code,
        remark: this.model.remark,
        create_time: this.model.createTime,
        create_by: name,
        outbound_type: this.model.outboundType,
        warehouse_no: this.model.warehouseNo,
        department_workshop: this.model.departmentWorkshop,
        now_date: estar.toDate(new Date(), 'yyyy-MM-dd HH:mm:ss'),
        infos: this.bussOutboundOrderInformationTable.dataSource,
      }
      var info = []
      info.push(params)
      console.log(params)
      let token = store.getters.token
      let id = this.selectedRowKeys[0]
      console.log('预览')
      window.open(
        `${window._CONFIG['domianURL']}/jmreport/view/979158814296924160?token=${token}&info=${info}`,
        '_blank'
      )
      // this.$router.push({path:'/business/outbound/PrintPreviewForm',query: {id:id,token:token,info: params }})
    },
    handleEditClosed({ row, column, cellValue, $table }) {
      this.selectionRows = [];
      console.log(row)
      let _this = this
      if (row.quantity > row.availableQuantity) {
        this.$message.error('输入的数量大于库存可用数量！')
        row.quantity = null
        return
      }
      console.log(row.quantity)
      if (row.quantity == null || row.quantity === '') {
        return
      }
      let detailList = _this.dataSource
      console.log(detailList)
      var quantity = parseFloat(row.quantity)
      console.log('quantity')

      console.log(quantity)
      for (let index = 0; index < detailList.length; index++) {
        var datas = detailList[index]
        console.log('datas')
        console.log(datas)
        // detailList.forEach(data => {
        if (row.materialId === datas.materialId) {
          for (let cindex = 0; cindex < datas.children.length; cindex++) {
            var data = datas.children[cindex]
            console.log('data')
            console.log(data)
            if (data.inventoryQuantity) {
              var max = parseFloat(data.inventoryQuantity)
              var out = 0
              var zhanyong = 0
              if (data.outputQuantity != null) {
                out = parseFloat(data.outputQuantity)
              }
              if (data.occupationQuantity != null) {
                zhanyong = parseFloat(data.occupationQuantity)
              }
              max = max - out - zhanyong
              data.quantity = quantity
              console.log('quantity')
              console.log(quantity)
              if (max >= quantity) {
                console.log('quantity1')
                data.quantity = quantity
                this.selectedRowKeys.push(data.id)
                console.log("this.selectionRows.push1")
                console.log(this.selectionRows)
                this.selectionRows.push(data)
                break
              } else {
                data.quantity = max
                console.log('quantity2')
                this.selectedRowKeys.push(data.id)
                                console.log("this.selectionRows.push2")
console.log(this.selectionRows)
                this.selectionRows.push(data)
                quantity = quantity - max
              }
            }
          }
        }
        // })
      }
      console.log('quantity')

      console.log(quantity)
      _this.dataSource = detailList
    },
    //处理每一行出库信息
    dealOutRows(row) {
      this.selectionRows = [];
      console.log(row)
      let _this = this
      if (row.quantity > row.availableQuantity) {
        this.$message.error('输入的数量大于库存可用数量！')
        row.quantity = null
        return
      }
      console.log('row.quantity')
      console.log(row.quantity)
      if (row.quantity == null || row.quantity === '') {
        return
      }
      console.log(_this.dataSource)
      let detailList = _this.dataSource
      console.log('detailList')
      console.log(detailList)
      var quantity = parseFloat(row.quantity)
      console.log('quantity')
      console.log(quantity)
      console.log('detailList')
      console.log(detailList)
      console.log(detailList)
      console.log(detailList[0])
      console.log('detailList.length')
      console.log(detailList.length)

      for (let index = 0; index < detailList.length; index++) {
        console.log('datas')
        var datas = detailList[index]

        console.log(datas)
        console.log('datas.materialId')
        console.log(row.materialId)
        // detailList.forEach(data => {
        if (row.materialId === datas.materialId) {
          console.log(datas.materialId)
          for (let cindex = 0; cindex < datas.children.length; cindex++) {
            var data = datas.children[cindex]
            console.log('data')
            console.log(data)
            if (data.inventoryQuantity) {
              var max = parseFloat(data.inventoryQuantity)
              var out = 0
              var zhanyong = 0
              if (data.outputQuantity != null) {
                out = parseFloat(data.outputQuantity)
              }
              if (data.occupationQuantity != null) {
                zhanyong = parseFloat(data.occupationQuantity)
              }
              max = max - out - zhanyong
              data.quantity = quantity
              console.log('quantity')
              console.log(quantity)
              if (max >= quantity) {
                data.quantity = quantity
                this.selectedRowKeys.push(data.id)
                                console.log("this.selectionRows.push3")
console.log(this.selectionRows)
                this.selectionRows.push(data)
                break
              } else {
                data.quantity = max
                this.selectedRowKeys.push(data.id)
                                console.log("this.selectionRows.push4")
console.log(this.selectionRows)
                this.selectionRows.push(data)
                quantity = quantity - max
              }
            }
          }
        }
        // })
      }
      console.log('quantity111')

      console.log(quantity)
      _this.dataSource = detailList
    },
    cellStyle({ row, column }) {
      if (column.property === 'quantity') {
        return 'background-color: #00FFFF;'
      }
      return ''
    },
  },
}
</script>

<style scoped>
</style>